package com.dxy.lc.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.dxy.lc.base.UnifiedException;
import com.dxy.lc.mapper.UserMapper;
import com.dxy.lc.model.entity.Dept;
import com.dxy.lc.mapper.DeptMapper;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
* <p>
*  服务实现类
* </p>
*
* @author dxy
* @since 2024-11-07
*/
@Slf4j
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    private static final String DEFAULT_PARENT_ID = "-1";

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(Dept entity) {
        Assert.notBlank(entity.getName(), "部门名称不能为空");
        // 填充菜单编码和排序号（考虑到没有高并发，故不加同步锁，另外有主键约束也不会成功插入）
        fillDeptIdAndSort(entity);
        baseMapper.insert(entity);
    }

    @Override
    public void updById(Dept entity) {
        Assert.notBlank(entity.getId(), "部门编码不能为空");
        baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delByIds(List<String> ids) {
        ids.forEach(deptId -> {
            // 检查是否有用户
            if (userMapper.selectCount(new LambdaQueryWrapper<User>().likeRight(User::getDeptId,deptId)) > 0){
                throw new UnifiedException(500,"部门{}或其子部门下存在用户",deptId);
            }else {
                baseMapper.deleteById(deptId);
            }
        });
    }

    @Override
    public Dept getDetail(String id) {
        Dept dept = baseMapper.selectById(id);
        if (dept != null){
            Dept parent = baseMapper.selectById(dept.getParentId());
            dept.setParentDeptName(parent != null ? parent.getName() : "");
        }
        return dept;
    }


    private void fillDeptIdAndSort(Dept entity) {
        String id = null;
        int sort = 0;
        String parentId = entity.getParentId();
        if (StrUtil.isBlank(parentId)) {
            entity.setParentId(DEFAULT_PARENT_ID);
            String maxId = baseMapper.getMaxIdByParentId(entity.getParentId());
            sort = getSort("", maxId);
            id = String.format("%02d", sort);
        } else {
            Dept parent = baseMapper.selectById(parentId);
            Assert.notNull(parent, "父部门{}不存在", parentId);
            String maxId = baseMapper.getMaxIdByParentId(parentId);
            sort = getSort(parentId, maxId);
            id = parentId + String.format("%02d", sort);
        }
        entity.setId(id);
        if (entity.getSort() == null) {
            entity.setSort(sort);
        }
    }

    private int getSort(String prefix, String maxId) {
        if (StrUtil.isEmpty(maxId)) {
            return 1;
        } else {
            if (StrUtil.isNotEmpty(prefix)){
                maxId = maxId.replaceFirst(prefix, "");
            }
            int pre = Integer.parseInt(maxId);
            int next = pre + 1;
            if (next > 99) {
                throw new UnifiedException(500, "同一父部门下的子部门数不能超过99个，请合理划分部门");
            }
            return next;
        }
    }

}
